<!DOCTYPE html>


  <html class="dark page-post">


<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="utf-8">
  
  <title>Vue编码技巧与规范 | Poetry&#39;s Blog</title>

  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

  
    <meta name="keywords" content="Vue,">
  

  <meta name="description" content="一、使用对象代替 if 及 switch 在很多情况下，我们经常会遇到循环判断执行赋值操作的场景，一般我们都会使用 if 及 switch 的条件判断，如果符合则执行赋值，不符合则进入下个判断，比如  let name = &apos;lisi&apos;;let age = 18;if (name === &apos;zhangsan&apos;) &amp;#123;    age = 21;&amp;#125; else if (name ===">
<meta name="keywords" content="Vue">
<meta property="og:type" content="article">
<meta property="og:title" content="Vue编码技巧与规范">
<meta property="og:url" content="http://blog.poetries.top/2019/06/01/vue-code-skill/index.html">
<meta property="og:site_name" content="Poetry&#39;s Blog">
<meta property="og:description" content="一、使用对象代替 if 及 switch 在很多情况下，我们经常会遇到循环判断执行赋值操作的场景，一般我们都会使用 if 及 switch 的条件判断，如果符合则执行赋值，不符合则进入下个判断，比如  let name = &apos;lisi&apos;;let age = 18;if (name === &apos;zhangsan&apos;) &amp;#123;    age = 21;&amp;#125; else if (name ===">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://user-gold-cdn.xitu.io/2018/11/1/166cafdda21ccc5b">
<meta property="og:updated_time" content="2020-08-15T04:25:31.938Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Vue编码技巧与规范">
<meta name="twitter:description" content="一、使用对象代替 if 及 switch 在很多情况下，我们经常会遇到循环判断执行赋值操作的场景，一般我们都会使用 if 及 switch 的条件判断，如果符合则执行赋值，不符合则进入下个判断，比如  let name = &apos;lisi&apos;;let age = 18;if (name === &apos;zhangsan&apos;) &amp;#123;    age = 21;&amp;#125; else if (name ===">
<meta name="twitter:image" content="https://user-gold-cdn.xitu.io/2018/11/1/166cafdda21ccc5b">

  

  
    <link rel="icon" href="/favicon.ico">
  

  <link href="/css/styles.css?v=c114cbeddx" rel="stylesheet">
<link href="/css/other.css?v=c114cbeddx" rel="stylesheet">


  
    <link rel="stylesheet" href="/css/personal-style.css">
  

  

  
  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "//hm.baidu.com/hm.js?40b1f89aa80f2527b3db779c6898c879";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>


  
  <script type="text/javascript">
	(function(){
	    var bp = document.createElement('script');
	    var curProtocol = window.location.protocol.split(':')[0];
	    if (curProtocol === 'https') {
	        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
	    }
	    else {
	        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
	    }
	    var s = document.getElementsByTagName("script")[0];
	    s.parentNode.insertBefore(bp, s);
	})();
  </script>



  
    <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <link rel="stylesheet" href="//cdn.bootcss.com/font-awesome/4.3.0/css/font-awesome.min.css">
  

  <!-- 聊天系统 -->
  
    
   <link type="text/css" rel="stylesheet" href="/renxi/default.css">
   <style>
      #modal {
        position: static !important;
      }
      .filter {
        width: 100%;
        height: 100%;
        position: absolute;
        top: 0;
        left: 0;
        background: #fe5757;
        animation: colorChange 30s ease-in-out infinite;
        animation-fill-mode: both;
        mix-blend-mode: overlay;
      }
  
      @keyframes colorChange {
        0%, 100% {
            opacity: 0;
        }
        50% {
            opacity: .9;
        }
      }
   </style>
</head>
</html>
<body>
  
  
    <span id="toolbox-mobile" class="toolbox-mobile">导航</span>
  

  <div class="post-header CENTER">
   
  <div class="toolbox">
    <a class="toolbox-entry" href="/">
      <span class="toolbox-entry-text">导航</span>
      <i class="icon-angle-down"></i>
      <i class="icon-home"></i>
    </a>
    <ul class="list-toolbox">
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/archives/"
            rel="noopener noreferrer"
            target="_self"
            >
            博客
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/categories/"
            rel="noopener noreferrer"
            target="_self"
            >
            分类
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/tags/"
            rel="noopener noreferrer"
            target="_self"
            >
            标签
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/search/"
            rel="noopener noreferrer"
            target="_self"
            >
            搜索
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/link/"
            rel="noopener noreferrer"
            target="_self"
            >
            友链
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/about/"
            rel="noopener noreferrer"
            target="_self"
            >
            关于
          </a>
        </li>
      
    </ul>
  </div>


</div>


  <div id="toc" class="toc-article">
    <strong class="toc-title">文章目录<i class="iconfont toc-title" style="display:inline-block;color:#87998d;width:20px;height:20px;">&#xf004b;</i></strong>
    <ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#一、使用对象代替-if-及-switch"><span class="toc-text">一、使用对象代替 if 及 switch</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#二、使用-Array-from-快速生成数组"><span class="toc-text">二、使用 Array.from 快速生成数组</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#三、使用-router-beforeEach-来处理跳转前逻辑"><span class="toc-text">三、使用 router.beforeEach 来处理跳转前逻辑</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#四、使用-v-if-来优化页面加载"><span class="toc-text">四、使用 v-if 来优化页面加载</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#五、路由跳转尽量使用-name-而不是-path"><span class="toc-text">五、路由跳转尽量使用 name 而不是 path</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#六、使用-key-来优化-v-for-循环"><span class="toc-text">六、使用 key 来优化 v-for 循环</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#七、使用-computed-代替-watch"><span class="toc-text">七、使用 computed 代替 watch</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#八、统一管理缓存变量"><span class="toc-text">八、统一管理缓存变量</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#九、不要使用-for-in-循环来遍历数组"><span class="toc-text">九、不要使用 for in 循环来遍历数组</span></a></li></ol>
  </div>
  




<div class="content content-post CENTER">
   <!-- canvas 彩带 -->
<canvas id="evanyou" width="1302" height="678" style="position: fixed;width: 100%;height: 100%;top: 0;left:0;z-index:-1;"></canvas>

<article id="post-vue-code-skill" class="article article-type-post" itemprop="blogPost">
  <header class="article-header" style="position:relative;">
    <h1 class="post-title">Vue编码技巧与规范</h1>

    <div class="article-meta">
      <span>
        <i class="icon-calendar"></i>
        <span>2019.06.02</span>
      </span>

      
        <span class="article-author">
          <i class="icon-user"></i>
          <span>Poetry</span>
        </span>
      

      
  <span class="article-category">
    <i class="icon-list"></i>
    <a class="article-category-link" href="/categories/Front-End/">Front-End</a>
  </span>



      

      
      <i class="fa fa-eye"></i> 
        <span id="busuanzi_container_page_pv">
           &nbsp热度 <span id="busuanzi_value_page_pv">
           <i class="fa fa-spinner fa-spin"></i></span>℃
        </span>
      
      
       
          <span class="post-count">
            <i class="fa fa-file-word-o"></i>&nbsp
            <span>字数统计 1.8k字</span>
          </span>

          <span class="post-count">
            <i class="fa fa-columns"></i>&nbsp
            <span>阅读时长 7分</span>
          </span>
      
      
    </div>

    <i class="iconfont" id="toc-eye" style="display:inline-block;color:#b36619;position:absolute;top:0;right:0;cursor:pointer;
    font-size: 24px;">&#xe61c;</i>

  </header>

  <div class="article-content">
    
      <div id="container">
        <h2 id="一、使用对象代替-if-及-switch"><a href="#一、使用对象代替-if-及-switch" class="headerlink" title="一、使用对象代替 if 及 switch"></a>一、使用对象代替 if 及 switch</h2><blockquote>
<p>在很多情况下，我们经常会遇到循环判断执行赋值操作的场景，一般我们都会使用 if 及 switch 的条件判断，如果符合则执行赋值，不符合则进入下个判断，比如</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">let</span> name = <span class="string">'lisi'</span>;</span><br><span class="line"><span class="keyword">let</span> age = <span class="number">18</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> (name === <span class="string">'zhangsan'</span>) &#123;</span><br><span class="line">    age = <span class="number">21</span>;</span><br><span class="line">&#125; <span class="keyword">else</span> <span class="keyword">if</span> (name === <span class="string">'lisi'</span>) &#123;</span><br><span class="line">    age = <span class="number">18</span>;</span><br><span class="line">&#125; <span class="keyword">else</span> <span class="keyword">if</span> (name === <span class="string">'wangwu'</span>) &#123;</span><br><span class="line">    age = <span class="number">12</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 或者</span></span><br><span class="line"><span class="keyword">switch</span>(name) &#123;</span><br><span class="line">    <span class="keyword">case</span> <span class="string">'zhangsan'</span>:</span><br><span class="line">        age = <span class="number">21</span>;</span><br><span class="line">        <span class="keyword">break</span></span><br><span class="line">    <span class="keyword">case</span> <span class="string">'lisi'</span>:</span><br><span class="line">        age = <span class="number">18</span>;</span><br><span class="line">        <span class="keyword">break</span></span><br><span class="line">    <span class="keyword">case</span> <span class="string">'wangwu'</span>:</span><br><span class="line">        age = <span class="number">12</span>;</span><br><span class="line">        <span class="keyword">break</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<blockquote>
<p>这样的写法不仅冗余，而且代码执行效率不高，我们可以使用对象的形式简写</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">let</span> name = <span class="string">'lisi'</span>;</span><br><span class="line"><span class="keyword">let</span> obj = &#123;</span><br><span class="line">    zhangsan: <span class="number">21</span>,</span><br><span class="line">    lisi: <span class="number">18</span>,</span><br><span class="line">    wangwu: <span class="number">12</span></span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> age = obj[name] || <span class="number">18</span>;</span><br></pre></td></tr></table></figure>
<blockquote>
<p>以上这种技巧适用于循环判断一次赋值的情况，如果判断过后有较多处理逻辑的还需要使用 <code>if</code> 或 <code>switch</code>等方法</p>
</blockquote>
<h2 id="二、使用-Array-from-快速生成数组"><a href="#二、使用-Array-from-快速生成数组" class="headerlink" title="二、使用 Array.from 快速生成数组"></a>二、使用 Array.from 快速生成数组</h2><blockquote>
<p>一般我们生成一个有规律的数组会使用循环插入的方法，比如使用时间选择插件时，我们可能需要将小时数存放在数组中</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">let</span> hours = [];</span><br><span class="line"></span><br><span class="line"><span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; <span class="number">24</span>; i++) &#123;</span><br><span class="line">    hours.push(i + <span class="string">'时'</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">let</span> hours = <span class="built_in">Array</span>.from(&#123; <span class="attr">length</span>: <span class="number">24</span> &#125;, (value, index) =&gt; index + <span class="string">'时'</span>);</span><br></pre></td></tr></table></figure>
<h2 id="三、使用-router-beforeEach-来处理跳转前逻辑"><a href="#三、使用-router-beforeEach-来处理跳转前逻辑" class="headerlink" title="三、使用 router.beforeEach 来处理跳转前逻辑"></a>三、使用 router.beforeEach 来处理跳转前逻辑</h2><blockquote>
<p>在某些情况下，我们需要在路由跳转前处理一些特定的业务逻辑，比如修改路由跳转、设置 <code>title</code> 等，代码如下</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> Vue <span class="keyword">from</span> <span class="string">'vue'</span></span><br><span class="line"><span class="keyword">import</span> Router <span class="keyword">from</span> <span class="string">'vue-router'</span></span><br><span class="line"></span><br><span class="line">Vue.use(Router)</span><br><span class="line"></span><br><span class="line"><span class="comment">// 首页</span></span><br><span class="line"><span class="keyword">const</span> Home = (<span class="function"><span class="params">resolve</span> =&gt;</span> &#123;</span><br><span class="line">    <span class="built_in">require</span>.ensure([<span class="string">'../views/home.vue'</span>], () =&gt; &#123;</span><br><span class="line">        resolve(<span class="built_in">require</span>(<span class="string">'../views/home.vue'</span>))</span><br><span class="line">    &#125;)</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> base = <span class="string">`<span class="subst">$&#123;process.env.BASE_URL&#125;</span>`</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> router =  <span class="keyword">new</span> Router(&#123;</span><br><span class="line">    mode: <span class="string">'history'</span>,</span><br><span class="line">    base: base,</span><br><span class="line">    routes: [</span><br><span class="line">        &#123;</span><br><span class="line">            path: <span class="string">'/'</span>,</span><br><span class="line">            name: <span class="string">'home'</span>,</span><br><span class="line">            component: Home,</span><br><span class="line">            meta: &#123; <span class="attr">title</span>: <span class="string">'首页'</span> &#125;</span><br><span class="line">        &#125;,</span><br><span class="line">    ]</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line">router.beforeEach(<span class="function">(<span class="params">to, <span class="keyword">from</span>, next</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">let</span> title = to.meta &amp;&amp; to.meta.title;</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">if</span> (title) &#123;</span><br><span class="line">        <span class="built_in">document</span>.title = title; <span class="comment">// 设置页面 title</span></span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">if</span> (to.name === <span class="string">'home'</span>) &#123;</span><br><span class="line">    </span><br><span class="line">        <span class="comment">// 拦截并跳转至 page2 单页，$openRouter 方法在第 5 节中封装</span></span><br><span class="line">        Vue.$openRouter(&#123;</span><br><span class="line">            name: <span class="string">'page2'</span></span><br><span class="line">        &#125;);</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    next();</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> router</span><br></pre></td></tr></table></figure>
<blockquote>
<p>注意最后需要调用 <code>next()</code> 方法执行路由跳转。</p>
</blockquote>
<h2 id="四、使用-v-if-来优化页面加载"><a href="#四、使用-v-if-来优化页面加载" class="headerlink" title="四、使用 v-if 来优化页面加载"></a>四、使用 v-if 来优化页面加载</h2><blockquote>
<p>在 <code>Vue</code> 页面中，一些模块可能需要用户主动触发才会显示，比如弹框组件等这样的子组件，那么我们可以使用 <code>v-if</code> 来进行按需渲染，没必要一进页面就渲染所有模块。比如</p>
</blockquote>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">template</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">div</span> @<span class="attr">click</span>=<span class="string">"showModuleB = true"</span>&gt;</span><span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">module-b</span> <span class="attr">v-if</span>=<span class="string">"isShowModuleB"</span>&gt;</span><span class="tag">&lt;/<span class="name">module-b</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">template</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="javascript"><span class="keyword">import</span> moduleB <span class="keyword">from</span> <span class="string">'components/moduleB'</span></span></span><br><span class="line"><span class="javascript"><span class="keyword">export</span> <span class="keyword">default</span> &#123;</span></span><br><span class="line">    data() &#123;</span><br><span class="line"><span class="javascript">        <span class="keyword">return</span> &#123;</span></span><br><span class="line"><span class="javascript">            isShowModuleB: <span class="literal">false</span></span></span><br><span class="line">        &#125;  </span><br><span class="line">    &#125;,</span><br><span class="line">    components: &#123;</span><br><span class="line">        moduleB</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br></pre></td></tr></table></figure>
<blockquote>
<p>这样当 <code>isShowModuleB</code> 为 <code>false</code> 的时候便不会加载该模块下的代码，包括一些耗时的接口调用。当然 v-if 主要适用于代码量较多、用户点击不是很频繁的模块的显示隐藏，同时如果涉及到权限问题的代码都需要使用 <code>v-if</code>，而不是 <code>v-show</code></p>
</blockquote>
<h2 id="五、路由跳转尽量使用-name-而不是-path"><a href="#五、路由跳转尽量使用-name-而不是-path" class="headerlink" title="五、路由跳转尽量使用 name 而不是 path"></a>五、路由跳转尽量使用 name 而不是 path</h2><blockquote>
<p>我们前期配置的路由路径后期难免会进行修改，如果我们页面跳转的地方全是使用的 <code>path</code>，那么我们需要修改所有涉及该 path 的页面，这样不利于项目的维护。而相对于 <code>path</code>，<code>name</code> 使用起来就方便多了，因为其具有唯一性，即使我们修改了 <code>path</code>，还可以使用原来的 <code>name</code> 值进行跳转</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">this</span>.$router.push(&#123; </span><br><span class="line">    name: <span class="string">'page1'</span></span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"><span class="comment">// 而不是</span></span><br><span class="line"><span class="keyword">this</span>.$router.push(&#123; </span><br><span class="line">    path: <span class="string">'page1'</span></span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<h2 id="六、使用-key-来优化-v-for-循环"><a href="#六、使用-key-来优化-v-for-循环" class="headerlink" title="六、使用 key 来优化 v-for 循环"></a>六、使用 key 来优化 v-for 循环</h2><blockquote>
<p><code>v-for</code> 是 <code>Vue</code> 提供的基于源数据多次渲染元素或模板块的指令。正因为是数据驱动，所以在修改列表数据的时候，<code>Vue</code> 内部会根据 <code>key</code> 值去判断某个值是否被修改，其会重新渲染修改后的值，否则复用之前的元素</p>
</blockquote>
<blockquote>
<p>这里如果数据中存在唯一表示 <code>id</code>，则推荐使用 <code>id</code> 作为 <code>key</code>，如果没有则可以使用数组的下标 <code>index</code> 作为 <code>key</code>。因为如果在数组中间插入值，其之后的 <code>index</code> 会发生改变，即使数据没变 <code>Vue</code> 也会进行重新渲染，所以最好的办法是使用数组中不会变化且唯一的那一项作为 <code>key</code> 值。例如</p>
</blockquote>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">template</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">ul</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">li</span> <span class="attr">v-for</span>=<span class="string">"(item, index) in arr"</span> <span class="attr">:key</span>=<span class="string">"item.id"</span>&gt;</span>&#123;&#123; item.data &#125;&#125;<span class="tag">&lt;/<span class="name">li</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">ul</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">template</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="javascript"><span class="keyword">export</span> <span class="keyword">default</span> &#123;</span></span><br><span class="line">    data() &#123;</span><br><span class="line"><span class="javascript">        <span class="keyword">return</span> &#123;</span></span><br><span class="line">            arr: [</span><br><span class="line">                &#123;</span><br><span class="line">                    id: 1,</span><br><span class="line"><span class="javascript">                    data: <span class="string">'a'</span></span></span><br><span class="line">                &#125;,</span><br><span class="line">                &#123;</span><br><span class="line">                    id: 2,</span><br><span class="line"><span class="javascript">                    data: <span class="string">'b'</span></span></span><br><span class="line">                &#125;,</span><br><span class="line">                &#123;</span><br><span class="line">                    id: 3,</span><br><span class="line"><span class="javascript">                    data: <span class="string">'c'</span></span></span><br><span class="line">                &#125;</span><br><span class="line">            ]</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br></pre></td></tr></table></figure>
<h2 id="七、使用-computed-代替-watch"><a href="#七、使用-computed-代替-watch" class="headerlink" title="七、使用 computed 代替 watch"></a>七、使用 computed 代替 watch</h2><blockquote>
<p>很多时候页面会出现 <code>watch</code> 的滥用而导致一系列问题的产生，而通常更好的办法是使用 <code>computed</code> 属性，首先需要区别它们有什么区别</p>
</blockquote>
<ul>
<li><code>watch</code>：当监测的属性变化时会自动执行对应的回调函数</li>
<li><code>computed</code>：计算的属性只有在它的相关依赖发生改变时才会重新求值</li>
</ul>
<blockquote>
<p>其实它们在功能上还是有所区别的，但是有时候可以实现同样的效果，而 computed 会更胜一筹，比如</p>
</blockquote>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">template</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">div</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">"text"</span> <span class="attr">v-model</span>=<span class="string">"firstName"</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">"text"</span> <span class="attr">v-model</span>=<span class="string">"lastName"</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">span</span>&gt;</span>&#123;&#123; fullName &#125;&#125;<span class="tag">&lt;/<span class="name">span</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">span</span>&gt;</span>&#123;&#123; fullName2 &#125;&#125;<span class="tag">&lt;/<span class="name">span</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">template</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="javascript"><span class="keyword">export</span> <span class="keyword">default</span> &#123;</span></span><br><span class="line">    data() &#123;</span><br><span class="line">        reurn &#123;</span><br><span class="line"><span class="javascript">            firstName: <span class="string">''</span>,</span></span><br><span class="line"><span class="javascript">            lastName: <span class="string">''</span>,</span></span><br><span class="line"><span class="javascript">            fullName2: <span class="string">''</span></span></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;,</span><br><span class="line">    </span><br><span class="line"><span class="javascript">    <span class="comment">// 使用 computed</span></span></span><br><span class="line">    computed: &#123;</span><br><span class="line">        fullName() &#123;</span><br><span class="line"><span class="javascript">            <span class="keyword">return</span> <span class="keyword">this</span>.firstName + <span class="string">' '</span> + <span class="keyword">this</span>.lastName</span></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;,</span><br><span class="line">    </span><br><span class="line"><span class="javascript">    <span class="comment">// 使用 watch</span></span></span><br><span class="line">    watch: &#123;</span><br><span class="line"><span class="javascript">        firstName: <span class="function"><span class="keyword">function</span>(<span class="params">newVal, oldVal</span>) </span>&#123;</span></span><br><span class="line"><span class="javascript">            <span class="keyword">this</span>.fullName2 = newVal + <span class="string">' '</span> + <span class="keyword">this</span>.lastName;</span></span><br><span class="line">        &#125;,</span><br><span class="line"><span class="javascript">        lastName: <span class="function"><span class="keyword">function</span>(<span class="params">newVal, oldVal</span>) </span>&#123;</span></span><br><span class="line"><span class="javascript">            <span class="keyword">this</span>.fullName2 = <span class="keyword">this</span>.firstName + <span class="string">' '</span> + newVal;</span></span><br><span class="line">        &#125;,</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br></pre></td></tr></table></figure>
<blockquote>
<p>上方我们通过对比可以看到，在处理多数据联动的情况下，使用 computed 会更加合理一点。</p>
</blockquote>
<p><img src="https://user-gold-cdn.xitu.io/2018/11/1/166cafdda21ccc5b" alt></p>
<h2 id="八、统一管理缓存变量"><a href="#八、统一管理缓存变量" class="headerlink" title="八、统一管理缓存变量"></a>八、统一管理缓存变量</h2><p>在项目中或多或少会使用浏览器缓存，比如 <code>sessionStorage</code> 和 <code>localStorage</code>，当一个项目中存在很多这样的缓存存取情况的时候就会变得难以维护和管理，因为其就像全局变量一样散落在项目的各个地方，这时候我们应该将这些变量统一管理起来，放到一个或多个文件中去，比如</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="comment">/* types.js */</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">const</span> USER_NAME = <span class="string">'userName'</span>;</span><br><span class="line"><span class="keyword">export</span> <span class="keyword">const</span> TOKEN = <span class="string">'token'</span>;</span><br></pre></td></tr></table></figure>
<p>在需要存取的时候，直接引用</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123; USER_NAME, TOKEN &#125; <span class="keyword">from</span> <span class="string">'../types.js'</span></span><br><span class="line"></span><br><span class="line">sessionStorage[USER_NAME] = <span class="string">'张三'</span>;</span><br><span class="line">localStorage[TOKEN] = <span class="string">'xxx'</span>;</span><br></pre></td></tr></table></figure>
<p>使用这种方法的好处在于一旦我们需要修改变量名，直接修改管理文件中的值即可，无需修改使用它的页面，同时这也可以避免命名冲突等问题的出现，这类似于 vuex 中 mutations 变量的管理。</p>
<h2 id="九、不要使用-for-in-循环来遍历数组"><a href="#九、不要使用-for-in-循环来遍历数组" class="headerlink" title="九、不要使用 for in 循环来遍历数组"></a>九、不要使用 for in 循环来遍历数组</h2><p>大家应该都知道 for in 循环是用于遍历对象的，但它可以用来遍历数组吗？答案是可以的，因为数组在某种意义上也是对象，但是如果用其遍历数组会存在一些隐患：其会遍历数组原型链上的属性</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">let</span> arr = [<span class="number">1</span>, <span class="number">2</span>];</span><br><span class="line"></span><br><span class="line"><span class="keyword">for</span> (<span class="keyword">let</span> key <span class="keyword">in</span> arr) &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(arr[key]); <span class="comment">// 会正常打印 1, 2</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 但是如果在 Array 原型链上添加一个方法</span></span><br><span class="line"><span class="built_in">Array</span>.prototype.test = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;&#125;;</span><br><span class="line"></span><br><span class="line"><span class="keyword">for</span> (<span class="keyword">let</span> key <span class="keyword">in</span> arr) &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(arr[key]); <span class="comment">// 此时会打印 1, 2, ƒ () &#123;&#125;</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

      </div>
    
  </div>

</article>

<button class="assist-btn2 circle" id="assist_btn2" title="点亮屏幕" style="left: 27px; top: 152px;">
  <i class="iconfont" style="display:inline-block;color:red;width:20px;height:20px;">&#xe61d;</i>
</button>
<button class="assist-btn1 circle" id="assist_btn1" title="关闭屏幕亮度" style="left: 27px; top: 152px;">
  <i class="iconfont toc-title" style="display:inline-block;color:red;width:20px;height:20px;">&#xe61d;</i>
</button>


<script src="//cdn.bootcss.com/jquery/3.1.1/jquery.min.js"></script>	

<script src="https://my.openwrite.cn/js/readmore.js" type="text/javascript"></script>
<script>
  const btw = new BTWPlugin();
  btw.init({
    id: "container",
    blogId: "22699-1592137983091-414",
    name: "前端进阶之旅",
    qrcode: "https://poetries1.gitee.io/img-repo/2020/06/qrcode.jpg",
    keyword: "3a3b3c",
  });
</script>

<script type="text/javascript">

// white theme
var body = {color: "#555", background: "#000"};
var a_tag = {color: "#222"};
var header = { background: "#222"};
var logo_line_i = {background: "#222"};
// var post_code = {background: "#eee", color: "#222"};

function switch_theme() {
 $("body").css(body);
 $("a:not('.links-of-author-item a, .site-state-item a, .site-state-posts a, .feed-link a, .motion-element a, .post-tags a, .show-commit-cls a, #donate_board a')").css(a_tag);
 $(".header, .footer").css(header);
 $(".logo-line-before i, .logo-line-after i").css(logo_line_i);
 //$(".post code").css(post_code);
 $("#idhyt-surprise-ball #idhyt-surprise-ball-animation .drag").css(a_tag);
 $(".post-title-link, .posts-expand .post-meta, .post-comments-count, .disqus-comment-count, .post-category a, .post-nav-next a, .post-nav-item a").css(a_tag);
 
 // $("code").css({color: '#c5c8c6', background: '#1d1f21'});
 //$("#assist_btn1").hide(1500);
}

$(function () {
$("#assist_btn2").css("display","none");
 $("#assist_btn1").click(function() {
     switch_theme();
$("div#toc.toc-article").css({
 "background":"#eaeaea",
 "opacity":1
});
$(".toc-article ol").show();
$("#toc.toc-article .toc-title").css("color","#a98602");
$("#assist_btn1").css("display","none");
$("#assist_btn2").css("display","block");
 });
$("#assist_btn2").click(function() {
$("#assist_btn2").css("display","none");
$("#assist_btn1").css("display","block");
$("body").css("background","url(http://www.miaov.com/static/ie/images/news/bg.png)")
     $(".header, .footer").css("background","url(http://www.miaov.com/static/ie/images/news/bg.png)")
$(".toc-article ol").toggle(1000);
 });
});


//背景随机

var Y, O, E, L, B, C, T, z, N, S, A, I;
!function() {
var e = function() {
for (O.clearRect(0, 0, L, B), T = [{
x: 0,
y: .7 * B + C
}, {
x: 0,
y: .7 * B - C
}]; T[1].x < L + C;) t(T[0], T[1])
}, t = function(e, t) {
O.beginPath(), O.moveTo(e.x, e.y), O.lineTo(t.x, t.y);
var n = t.x + (2 * I() - .25) * C,
 r = a(t.y);
O.lineTo(n, r), O.closePath(), N -= S / -50, O.fillStyle = "#" + (127 * A(N) + 128 << 16 | 127 * A(N + S / 3) + 128 << 8 | 127 * A(N + S / 3 * 2) + 128).toString(16), O.fill(), T[0] = T[1], T[1] = {
 x: n,
 y: r
}
}, a = function n(e) {
var t = e + (2 * I() - 1.1) * C;
return t > B || t < 0 ? n(e) : t
};
Y = document.getElementById("evanyou"), O = Y.getContext("2d"), E = window.devicePixelRatio || 1, L = window.innerWidth, B = window.innerHeight, C = 90, z = Math, N = 0, S = 2 * z.PI, A = z.cos, I = z.random, Y.width = L * E, Y.height = B * E, O.scale(E, E), O.globalAlpha = .6, document.onclick = e, document.ontouchstart = e, e()
}()

   
$("#toc-eye").click(function(){
$("#toc.toc-article").toggle(1000);
});

</script>


   
  <div class="text-center donation">
    <div class="inner-donation">
      <span class="btn-donation">支持一下</span>
      <div class="donation-body">
        <div class="tip text-center">扫一扫，支持poetries</div>
        <ul>
        
          <li class="item">
            
              <span>微信扫一扫</span>
            
            <img src="/images/weixin.jpg" alt="">
          </li>
        
          <li class="item">
            
              <span>支付宝扫一扫</span>
            
            <img src="/images/zhifubao.jpg" alt="">
          </li>
        
        </ul>
      </div>
    </div>
  </div>


   
  <div class="box-prev-next clearfix">
    <a class="show pull-left" href="/2019/06/01/vue-opz/">
        <i class="icon icon-angle-left"></i>
    </a>
    <a class="show pull-right" href="/2019/06/01/vue-multiplexed-module/">
        <i class="icon icon-angle-right"></i>
    </a>
  </div>




</div>


  <a id="backTop" class="back-top">
    <i class="icon-angle-up"></i>
  </a>




  <div class="modal" id="modal">
  <span id="cover" class="cover hide"></span>
  <div id="modal-dialog" class="modal-dialog hide-dialog">
    <div class="modal-header">
      <span id="close" class="btn-close">关闭</span>
    </div>
    <hr>
    <div class="modal-body">
      <ul class="list-toolbox">
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/archives/"
              rel="noopener noreferrer"
              target="_self"
              >
              博客
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/categories/"
              rel="noopener noreferrer"
              target="_self"
              >
              分类
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/tags/"
              rel="noopener noreferrer"
              target="_self"
              >
              标签
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/search/"
              rel="noopener noreferrer"
              target="_self"
              >
              搜索
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/link/"
              rel="noopener noreferrer"
              target="_self"
              >
              友链
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/about/"
              rel="noopener noreferrer"
              target="_self"
              >
              关于
            </a>
          </li>
        
      </ul>

    </div>
  </div>
</div>



  
      <div class="fexo-comments comments-post">
    

    

    
    

    

    
    

    

<!-- Gitalk评论插件通用代码 -->
<div id="gitalk-container"></div>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.css">
<script src="https://cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.min.js"></script>
<script>
const gitalk = new Gitalk({
  clientID: '5567a2c4abb858009d96',
  clientSecret: 'b9039ec056cf5c2346b3cdb63308a28c163f91e5',
  repo: 'poetries.github.io',
  owner: 'poetries',
  // 在这里设置一下截取前50个字符串, 这是因为 github 对 label 的长度有了要求, 如果超过
  // 50个字符串则会报错.
  // id: location.pathname.split('/').pop().substring(0, 49),
  id: location.pathname,
  admin: ['poetries'],
  // facebook-like distraction free mode
  distractionFreeMode: false
})
gitalk.render('gitalk-container')
</script>
<!-- Gitalk代码结束 -->



  </div>

  

  <script type="text/javascript">
  function loadScript(url, callback) {
    var script = document.createElement('script')
    script.type = 'text/javascript';

    if (script.readyState) { //IE
      script.onreadystatechange = function() {
        if (script.readyState == 'loaded' ||
          script.readyState == 'complete') {
          script.onreadystatechange = null;
          callback();
        }
      };
    } else { //Others
      script.onload = function() {
        callback();
      };
    }

    script.src = url;
    document.getElementsByTagName('head')[0].appendChild(script);
  }

  window.onload = function() {
    loadScript('/js/bundle.js?235683', function() {
      // load success
    });
  }
</script>


  <!-- 页面点击小红心 -->
  <script type="text/javascript" src="/js/clicklove.js"></script>
 
  
</body>
</html>
